package com.gyg.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.Assert;
import com.gyg.entity.User;
import com.gyg.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    /**
     * 执行授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 执行认证
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//        根据用户名查找用户
        User user = userService.getOne(new QueryWrapper<User>().eq("username",((UsernamePasswordToken) token).getUsername()));

        if (user == null){
            return null;
        }
        if (!user.getPassword().equals(userToken.getPassword())){
//            Assert.fail("密码不正确！");
        }
        return new SimpleAuthenticationInfo(user,userToken.getPassword(),"");
    }
}
